package com.heoller.controller;

import com.heoller.dto.CustomParam;
import com.heoller.service.generator.GeneratorService;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * @author huliang
 * @date 2021-11-23 15:38
 */
@Controller
public class GeneratorController {

    @Autowired
    private GeneratorService generatorService;

    @PostMapping("/generate")
    public void generator(@RequestBody CustomParam customParam, HttpServletResponse response) throws IOException {
        byte[] data = generatorService.generate(customParam);

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=" + customParam.getArtifactId() + ".zip");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.write(data, outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
